//app.js
App({
  onLaunch: function () {
    //在线调试
    /*
    wx.setEnableDebug({
      enableDebug: true
    })
    */
    try {
      var userData = wx.getStorageSync('userData')
      if (userData) {
        if ("string" == typeof userData)
          userData = JSON.parse(userData);
        this.globalData.userData = userData;
      }
    } catch (e) {
    }
    this.loadUserinfo();
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    //新版本检测
    this.checkVersion();
  },
  /**
   * 新版本检测
   */
  checkVersion: function () {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        console.log('onCheckForUpdate====', res)
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          console.log('res.hasUpdate====')
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                console.log('success====', res)
                // res: {errMsg: "showModal: ok", cancel: false, confirm: true}
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
            })
          })
        }
      })
    }
  },
  onShow:function(){
    this.loadUserinfo();
  },
  loadUserinfo:function(){
    if (this.isLogin() && this.getMerchantId()==0) {
      var that = this;
      wx.request({
        url: this.globalData.apiUri + '/pub/merchant/getSelectedMerId',
        header: {
          'token': this.globalData.userData.token
        },
        method: 'GET',
        success(res) {
          var rdata = res.data;
          if (rdata.code == 0) {
            that.globalData.userData.merchantId = rdata.merchantId;
            try {
              wx.setStorageSync('userData', userData);
            } catch (e) {
            }
          }
        }
      });
    }
  },
  validateLogin: function () {
    // 没有登录，跳转授权页
    if (!this.isLogin()) {
      wx.navigateTo({
        url: '/pages/index/login',
      })
    }
  },
  isLogin:function(){
    var b=false;
    if(this.globalData.userData ){
      if (this.globalData.userData.userId && this.globalData.userData.userId > 0){
        b=true;
      }
    }
    return b;
  },
  getToken: function () {
    if (this.globalData.userData) {
      return this.globalData.userData.token;
    } else {
      return undefined;
    }
  },
  getUserId: function () {
    if (this.globalData.userData){
      return this.globalData.userData.userId;
    }
    return 0;
  },
  getMerchantId:function(){
    if (this.globalData.userData) {
      return this.globalData.userData.merchantId;
    }
    return 0;
  },
  getOpenid: function () {
    if (this.globalData.userData){
      return this.globalData.userData.openid;
    }else{
      return undefined;
    }
  },
  getUserData: function () {
    return this.globalData.userData;
  },
  globalData: {
    userData: { merchantId: 0, userId: 0, token:'159753456852'},//默认游客账户 
    apiUri: "http://localhost:8765/huijielong-api"
  }
})